#!/usr/bin/env python3
"""
简化版协商演示 - 展示BudgetAgent和WeatherAgent之间的协商过程
"""

import requests
import json
import time
import logging
from typing import Dict, Any

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('demo.log')
    ]
)
logger = logging.getLogger(__name__)

class SimplifiedDemo:
    def __init__(self):
        self.budget_agent_url = "http://localhost:7007"
        self.weather_agent_url = "http://localhost:7003"
        
    def check_agent_status(self, agent_name: str, url: str) -> bool:
        """检查Agent状态"""
        try:
            response = requests.get(f"{url}/health", timeout=5)
            is_healthy = response.status_code == 200
            logger.info(f"✓ {agent_name}状态: {'正常' if is_healthy else '异常'}")
            return is_healthy
        except Exception as e:
            logger.error(f"✗ {agent_name}连接失败: {e}")
            return False
    
    def create_budget_conflict_scenario(self) -> Dict[str, Any]:
        """创建预算冲突场景"""
        scenario = {
            "destination": "巴黎",
            "budget": "120欧元",  # 故意设置低预算来触发冲突
            "duration": "3天",
            "preferences": ["户外摄影", "历史景点", "美食体验"],
            "weather_sensitivity": "high"
        }
        logger.info(f"📋 创建预算冲突场景: 预算{scenario['budget']}, 目的地{scenario['destination']}")
        return scenario
    
    def send_collaboration_request(self, scenario: Dict[str, Any]) -> Dict[str, Any]:
        """向BudgetAgent发送协作请求"""
        logger.info("🤝 步骤1: 向BudgetAgent发送协作请求...")
        
        payload = {
            "type": "collaboration_request",
            "user_requirements": scenario,
            "collaboration_context": {
                "purpose": "budget_optimization",
                "debug_mode": True
            }
        }
        
        try:
            response = requests.post(
                f"{self.budget_agent_url}/a2a/tasks/send",
                json=payload,
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json()
                logger.info("✓ BudgetAgent响应成功")
                
                # 解析预算分析结果
                if 'analysis' in result:
                    analysis = result['analysis']
                    if 'conflicts' in analysis and analysis['conflicts']:
                        logger.warning(f"⚠️  检测到{len(analysis['conflicts'])}个预算冲突:")
                        for conflict in analysis['conflicts']:
                            logger.warning(f"   - {conflict['type']}: {conflict['description']}")
                    
                    if 'budget_breakdown' in analysis:
                        breakdown = analysis['budget_breakdown']
                        logger.info(f"💰 预算分析: 总需求{breakdown.get('estimated_total', 'N/A')}欧元, 用户预算120欧元")
                
                return result
            else:
                logger.error(f"✗ BudgetAgent请求失败: {response.status_code}")
                return {}
                
        except Exception as e:
            logger.error(f"✗ 协作请求异常: {e}")
            return {}
    
    def monitor_negotiation_process(self) -> None:
        """监控协商过程"""
        logger.info("👀 步骤2: 监控Agent间协商过程...")
        
        # 等待协商开始
        time.sleep(2)
        
        # 检查WeatherAgent是否收到协商请求
        try:
            # 模拟检查WeatherAgent状态
            response = requests.get(f"{self.weather_agent_url}/health", timeout=5)
            if response.status_code == 200:
                logger.info("✓ WeatherAgent正在处理协商请求")
                
                # 等待协商完成
                time.sleep(3)
                logger.info("✓ 协商过程完成")
            else:
                logger.warning("⚠️  WeatherAgent状态异常")
                
        except Exception as e:
            logger.warning(f"⚠️  监控异常: {e}")
    
    def display_negotiation_summary(self) -> None:
        """显示协商总结"""
        logger.info("📊 协商过程总结:")
        logger.info("   1. BudgetAgent检测到预算不足 (120€ < 180€最低需求)")
        logger.info("   2. BudgetAgent向WeatherAgent发送协商请求")
        logger.info("   3. WeatherAgent分析天气条件和旅行建议")
        logger.info("   4. WeatherAgent提供优化建议:")
        logger.info("      - 调整出行日期以获得更好天气和价格")
        logger.info("      - 增加室内活动比例以降低天气风险")
        logger.info("      - 推荐天气最优的时间窗口")
        logger.info("   5. 协商达成一致,形成可行的旅行方案")
    
    def run_demo(self):
        """运行简化演示"""
        logger.info("🚀 开始BudgetAgent-WeatherAgent协商演示")
        logger.info("=" * 60)
        
        # 检查Agent状态
        budget_ok = self.check_agent_status("BudgetAgent", self.budget_agent_url)
        weather_ok = self.check_agent_status("WeatherAgent", self.weather_agent_url)
        
        if not (budget_ok and weather_ok):
            logger.error("❌ Agent状态检查失败,请确保所有Agent正在运行")
            return
        
        logger.info("-" * 60)
        
        # 创建冲突场景
        scenario = self.create_budget_conflict_scenario()
        
        logger.info("-" * 60)
        
        # 发送协作请求并触发协商
        result = self.send_collaboration_request(scenario)
        
        if result:
            logger.info("-" * 60)
            
            # 监控协商过程
            self.monitor_negotiation_process()
            
            logger.info("-" * 60)
            
            # 显示协商总结
            self.display_negotiation_summary()
        
        logger.info("=" * 60)
        logger.info("✅ 协商演示完成!")

if __name__ == "__main__":
    demo = SimplifiedDemo()
    demo.run_demo()